import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Util from '@/utils/test.js'
import projectSetting from '@/settings/projectSetting.js'
import popup from '@/views/login/popup.js'
// 路由数据
import routes from './base'

/* Router Modules */
Vue.use(Router)
const router = new Router({
  mode: 'history',
  routes
})

const modulesFiles = require.context('./modules', true, /\.js$/)
modulesFiles.keys().forEach(modulePath => {
  let value = modulesFiles(modulePath)
  router.addRoutes(value.default)
})
// 路由拦截
router.beforeEach((to, from, next) => {
  const app_title =
    store.getters['projectSetting/getGlobSiteInfo'].title || projectSetting.globTitle

  /* 页面title */
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + app_title
  } else {
    document.title = app_title
  }

  // 判断 课程是否分享code
  if (Util.isEmpty(to.query.share_code)) {
    store.commit('projectSetting/setGlobShareCode', '')
  } else {
    store.commit('projectSetting/setGlobShareCode', to.query.share_code)
  }

  /* h5 分享课程链接跳转到对应的页面 */
  const exchangeList = [
    {
      name: 'topic',
      pc: '/topic/details',
      h5: '/pageFound/topic/details'
    },
    {
      name: 'mall',
      pc: '/mall/details',
      h5: '/pageFound/mall/details'
    },
    {
      name: 'user',
      pc: '/user',
      h5: '/pageFound/user/index'
    },
    {
      name: 'share',
      pc: '/exam/share',
      h5: '/pageFound/exam/share'
    },
    {
      name: 'agreement',
      pc: '/agreement',
      h5: '/pages/protocol'
    }
  ]
  const exchangeData = exchangeList.find(item => item.h5 == to.path)
  const regex = /^\/pageCourse\/course(\/[\w-]+)*$/
  if (regex.test(to.path)) {
    let query = {}
    if (to.query.share_code) {
      query.share_code = to.query.share_code
    }
    if (to.query.id) {
      next({
        path: `/course/${to.query.id}`,
        query: query
      })
    } else {
      next('/')
    }
  } else if (exchangeData) {
    if (exchangeData.name == 'teacher') {
      next({
        path: `${exchangeData.pc}/${to.query.id}`
      })
    } else if (exchangeData.name == 'agreement') {
      next({
        path: `${exchangeData.pc}/${to.query.key}`
      })
    } else {
      next({
        path: exchangeData.pc,
        query: to.query
      })
    }
  } else {
    /* 使用 name 或path两种情形进行跳转,没有找到的路由的情况下，跳转404 */
    if (to.matched.length !== 0) {
      /* 判断该路由是否需要登录权限,不需要权限的或已经登陆的直接执行下一步 */
      if (
        to.matched.some(record => record.meta.needLogin === false) ||
        store.getters['user/isLogin']
      ) {
        next()
      } else {
        // 需要授权的,未登录的情况下,跳转到登陆
        popup.install({
          currentTab: store.getters['projectSetting/getGlobLoginRouteName'],
          visible: true
        })
      }
    } else {
      next({ path: '/404' })
    }
  }
})

// 解决重复点击导航路由报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

router.afterEach(to => {
  window.scroll(0, 0)
})

export default router
